﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using QuantitativeIndicator.Tools;

namespace QuantitativeIndicator.FundStkRatio
{
    class FundStkRatioDataModel:DataModel
    {
        /*calDate代表计算日,type代表基金组织类型（开放or封闭），isIndex代表是否为指数基金，fundInvestType代表基金是股票型还是混合型
        此方法获取calDate当前存在的股票列表以及基金持有数量*/
         public Dictionary<string,double> getStartPortfolio(string calDate,string type,string isIndex,string fundInvestType)
        {
            Dictionary<string,double> tmpDic=new Dictionary<string,double>();
            string stopDate = getLastStopDate(calDate);

            windCommand.CommandText = "select stockCode as stkCode,sum(volume) as holdAmount from fundPortfolio,fundList where fundList.tradingCode=fundPortfolio.fundTradingCode and stopDate='"+stopDate+"' and fundList.type='"+type+"' and fundList.isIndex='"+isIndex+"' and fundList.investmentType='"+fundInvestType+"' group by fundPortfolio.stockCode order by stockCode";
            SqlDataReader sdr = windCommand.ExecuteReader();
            while (sdr.Read())
            {
                tmpDic.Add(sdr["stkCode"].ToString(),double.Parse(sdr["holdAmount"].ToString()));
            }
            sdr.Close();
            return tmpDic ;
        }

        //得到最近一个可编程的公告日，0630 or 1231
        public string getLastStopDate(string calDate)
        {
            string maxIssueDate=null;
            string tmpStopDate;
            string yearStr;
            string monthStr;
            yearStr = calDate.Substring(0,4);
            monthStr = calDate.Substring(4, 4);

            const string reportMonthStr1 = "0630";
            const string reportMonthStr2 = "1231";

            if (int.Parse(monthStr) > int.Parse(reportMonthStr1))
            {
                tmpStopDate = yearStr + reportMonthStr1;
            }
            else 
            {
                yearStr=(int.Parse(yearStr)-1).ToString();
                tmpStopDate = yearStr + reportMonthStr2;
            }
            windCommand.CommandText = "select max(issueDate) as maxIssueDate from dbo.fundPortfolio where stopDate=" + tmpStopDate;
            SqlDataReader sdr = windCommand.ExecuteReader();
            if (sdr.Read())
            {
                maxIssueDate = sdr["maxIssueDate"].ToString();
            }
            sdr.Close();
            //这里很重要，只有当calDate大于最后一个公布基金持股日期时，才会更新stopDate,等于则不会更新
            if (int.Parse(maxIssueDate) >= int.Parse(calDate))
            {
                if (tmpStopDate.Substring(4, 4) == "0630")
                {
                    tmpStopDate = (int.Parse(tmpStopDate.Substring(0, 4))-1).ToString() + reportMonthStr2;
                }
                else
                {
                    tmpStopDate = tmpStopDate.Substring(0, 4) + reportMonthStr1; 
                }
            }
            return tmpStopDate;
        }

        //得到指数成分股组合调整的起始日,起始日这里为max(issueDate)。注意：起始日的指数收益率问题
        public string getPortfolioStartDate(string calDate)
        {
            string tmpDate=null;
            string tmpStopDate = getLastStopDate(calDate);

            windCommand.CommandText = "select max(issueDate) as maxIssueDate from fundPortfolio where fundPortfolio.stopDate='"+tmpStopDate+"'";
            SqlDataReader sdr = windCommand.ExecuteReader();
            if (sdr.Read())
            {
                tmpDate = sdr["maxIssueDate"].ToString();
            }
            sdr.Close();
            return tmpDate;
        }

        //设定指数编制的基期为20050101，基点1000点
        public void setBasePoint(string type, string isIndex, string fundInvestType)
        {
            windCommand.CommandText = "insert into dbo.DFZQ_FundHoldStockIndex values('20050101','"+type+"','"+isIndex+"','"+fundInvestType+"',1000,1000)";
            windCommand.ExecuteNonQuery();
        }
        
        //得到DFZQ_FundHoldStockIndex中的最近一个编制日期,如无则返回null
        public string getDFZQ_FundHoldStockIndexLatestDate(string type, string isIndex, string fundInvestType)
        {
            string tmpDate=null;
            windCommand.CommandText = "select max(tradingDate) as maxDate from DFZQ_FundHoldStockIndex where type='"+type+"' and isIndex='"+isIndex+"' and investmentType='"+fundInvestType+"'";
            SqlDataReader sdr = windCommand.ExecuteReader();
            if (sdr.Read())
            {
                if (sdr["maxDate"] is DBNull)
                {
                    tmpDate = null;
                }
                else
                {
                    tmpDate = sdr["maxDate"].ToString();
                }
            }
            sdr.Close();
            return tmpDate;
        }
        
        //插入DFZQ_FundHoldStockIndex表
        public void insertDFZQ_FundHoldStockIndex(string tradingDate, string type, string isIndex, string fundInvestType, double closePrice, double lastClosePrice)
        {
            windCommand.CommandText = "insert into DFZQ_FundHoldStockIndex values('" + tradingDate + "','" + type + "','" + isIndex + "','" + fundInvestType + "'," + closePrice + "," + lastClosePrice + ")";
            windCommand.ExecuteNonQuery();
        }
        
        //得到DFZQ_FundHoldStockIndex的最新收盘价,如没有则返回0
        public double getDFZQ_FundHoldStockIndexClosePrice(string type, string isIndex, string fundInvestType)
        {
            double tmpCP=0;
            windCommand.CommandText = "select top 1 closePrice from DFZQ_FundHoldStockIndex where type='" + type + "' and isIndex='" + isIndex + "' and investmentType='" + fundInvestType + "' order by tradingDate desc";
            SqlDataReader sdr = windCommand.ExecuteReader();
            if (sdr.Read())
            {
                tmpCP = double.Parse(sdr["closePrice"].ToString());
            }
            return tmpCP;
        }
        
        //得到上一交易日
        public string getLastTradingDate(string calDate)
        {
            string tmpDate;
            windCommand.CommandText = "SELECT top 1 tradingDate FROM tradingDates where tradingDate<" + calDate + " order by tradingDate desc";
            SqlDataReader sdr=windCommand.ExecuteReader();
            sdr.Read();
            tmpDate = sdr["tradingDate"].ToString();
            sdr.Close();
            return tmpDate;
        }
        
        //得到基金的成立日期，如果为NULL，则返回null
        public string getFundFoundDate(string fundCode)
        {
            string tmpDate=null;
            windCommand.CommandText = "select foundDate from fundList where tradingCode='" + fundCode + "'";
            SqlDataReader sdr = windCommand.ExecuteReader();
            if (sdr.Read())
            {
                tmpDate = sdr["foundDate"].ToString();
            }
            sdr.Close();
            return tmpDate;
        }


    }
}
